package com.aipartner.service.impl;

import com.aipartner.entity.UserWorkLike;
import com.aipartner.mapper.UserWorkLikeMapper;
import com.aipartner.service.UserWorkLikeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户作品点赞服务实现
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Slf4j
@Service
public class UserWorkLikeServiceImpl extends ServiceImpl<UserWorkLikeMapper, UserWorkLike> implements UserWorkLikeService {
    
    @Override
    @Transactional
    public Boolean toggleLike(Long workId, Long userId) {
        try {
            // 检查是否已点赞
            QueryWrapper<UserWorkLike> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("work_id", workId).eq("user_id", userId);
            UserWorkLike existingLike = this.getOne(queryWrapper);
            
            boolean liked;
            if (existingLike != null) {
                // 已点赞，取消点赞
                this.removeById(existingLike.getId());
                liked = false;
                log.info("用户 {} 取消点赞作品 {}", userId, workId);
            } else {
                // 未点赞，添加点赞
                UserWorkLike like = new UserWorkLike();
                like.setWorkId(workId);
                like.setUserId(userId);
                like.setCreateTime(LocalDateTime.now());
                this.save(like);
                liked = true;
                log.info("用户 {} 点赞作品 {}", userId, workId);
            }
            
            // 更新作品点赞数
            baseMapper.updateWorkLikeCount(workId);
            
            return liked;
        } catch (Exception e) {
            log.error("切换点赞状态失败: workId={}, userId={}", workId, userId, e);
            throw new RuntimeException("点赞操作失败", e);
        }
    }
    
    @Override
    public Map<String, Object> getLikeInfo(Long workId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取点赞数
        int likeCount = baseMapper.getLikeCount(workId);
        result.put("likeCount", likeCount);
        
        // 检查当前用户是否已点赞
        if (userId != null) {
            boolean liked = baseMapper.isLikedByUser(workId, userId);
            result.put("liked", liked);
        } else {
            result.put("liked", false);
        }
        
        return result;
    }
    
    @Override
    public int getLikeCount(Long workId) {
        return baseMapper.getLikeCount(workId);
    }
    
    @Override
    public boolean isLikedByUser(Long workId, Long userId) {
        if (userId == null) {
            return false;
        }
        return baseMapper.isLikedByUser(workId, userId);
    }
}
